package com.sd.sdk.client;

import com.sd.sdk.core.exception.ApiException;
import com.sd.sdk.core.exception.ApiTimeOutException;
import okhttp3.*;

import java.io.IOException;
import java.net.SocketTimeoutException;

class HttpUtil {

    private static final OkHttpClient CLIENT = new OkHttpClient();
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json");

    static String post(String url, String json) {
        RequestBody body = RequestBody.create(json ,MEDIA_TYPE);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = CLIENT.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return responseBody.string();
            }
        } catch (SocketTimeoutException e) {
            throw new ApiTimeOutException("接口超时", e);
        } catch (IOException e) {
            throw new ApiException("接口调用异常", e);
        }
        return null;
    }

}
